package dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import utils.DbUtil;

import dao.AdminDao;
import entity.Admin;

public class AdminDaoImpl implements AdminDao{

	public List<Admin> getList(int offset, int limit, String condition,
			String order) throws SQLException {
		StringBuffer sb = new StringBuffer();
		sb.append("select * from j_admin");
		if(!"".equals(condition)) {
			sb.append(" where "+condition+" ");
		}
		sb.append(order);
		sb.append(" limit "+offset+", "+limit);
		System.out.println("sql = "+sb.toString());
		return DbUtil.queryRunner().query(sb.toString(), new BeanListHandler<Admin>(Admin.class));
	}

	public int getListCount(String condition) throws SQLException {
		StringBuffer sb = new StringBuffer();
		sb.append("select count(*) from j_admin");
		if(!"".equals(condition)) {
			sb.append(" where "+condition+" ");
		}
		Long count = DbUtil.queryRunner().query(sb.toString(), new ScalarHandler<Long>());
		return count.intValue();
	}

	public int addAdmin(Admin admin) throws SQLException {
		Object[] params = {admin.getUsername(),admin.getPassword(),admin.getSalt(),admin.getDate_entered(),admin.getLogin_entered(),admin.getLast_login_entered(),admin.getLogin_ip(),admin.getRole_id(),admin.getStatus()};
		return DbUtil.queryRunner().update("insert into j_admin (username,password,salt,date_entered,login_entered,last_login_entered,login_ip,role_id,status) values (?,?,?,?,?,?,?,?,?)", params);
	}

	public int deleteAdminById(String id) throws SQLException {
		return DbUtil.queryRunner().update("delete from j_admin where id in(?)", id);
	}

	@SuppressWarnings("deprecation")
	public Admin getAdminById(int id) throws SQLException {
		return DbUtil.queryRunner().query("select * from j_admin where id=?", id, new BeanHandler<Admin>(Admin.class));
	}

	public int editAdmin(Admin admin) throws SQLException {
		StringBuffer sb = new StringBuffer();
		ArrayList<Object> params = new ArrayList<Object>();
		params.add(admin.getUsername());
		params.add(admin.getStatus());
		params.add(admin.getRole_id());
		sb.append("update j_admin set username=?,`status`=?, role_id=?");
		if(admin.getPassword() != null) {
			sb.append(",password=?");
			params.add(admin.getPassword());
		}
		sb.append(" where id=?");
		params.add(admin.getId());
		return DbUtil.queryRunner().update(sb.toString(), params.toArray());
	}

	@SuppressWarnings("deprecation")
	public Admin getAdminByUsername(String username) throws SQLException {
		return DbUtil.queryRunner().query("select * from j_admin where username=?", username, new BeanHandler<Admin>(Admin.class));
	}

}
